USE SAS
GO

 IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'InsUpdEmail')
	BEGIN
		DROP  Procedure  dbo.InsUpdEmail
	END
GO

CREATE Procedure dbo.InsUpdEmail (
	@EMAILID				VARCHAR(10)		= '0'
,	@PARTNEREMAIL			VARCHAR(200)	= ''
,	@ADDRESSTYPE			VARCHAR(10)		= '2'
,	@PARTNERGUID			VARCHAR(100)	= ''
,	@USERID					VARCHAR(10)		= '1'
)
AS
BEGIN
	
	IF EXISTS(SELECT 1 FROM TR_EMAIL WHERE EmailID = CAST(@EMAILID AS INT) )
	BEGIN		-- UPDATE
		UPDATE TR_EMAIL
		SET	PartnerEMAIL	= @PARTNEREMAIL
		,	AddressType		= @ADDRESSTYPE
		,	ChangedBy		= @USERID
		,	ChangeDate		= GETDATE()
		WHERE
			EmailID	= @EmailID
		AND	CAST(PartnerGuid AS VARCHAR(100)) = @PARTNERGUID
	END
	ELSE
	BEGIN		-- INSERT 
		SELECT @EMAILID	= ISNULL(MAX(EmailID), 0) +1 FROM TR_EMAIL

		INSERT INTO TR_EMAIL (EmailID,PartnerEmail,AddressType,PartnerGuid,
								CreatedBy,CreateDate,ChangedBy,ChangeDate)
		VALUES(
			@EMAILID			--EMAILID
		,	@PARTNEREMAIL		--PARTNEREMAIL
		,	@ADDRESSTYPE		--ADDRESSTYPE
		,	@PARTNERGUID		--PartnerGuid
		,	@USERID				--CreatedBy
		,	GETDATE()			--CreateDate
		,	@USERID				--ChangedBy
		,	GETDATE()			--ChangeDate
		)
	END
END
GO
